<template>
  <el-container v-loading="model.loading"  class="h-100">
    <el-header class="shadow-sm d-flex justify-content-between align-items-center bg-white" style="height: 80px;">
      <div>
        <el-button type="primary" @click="addUser">添加管理员</el-button>
        <span class="text-muted ml-3">总计: {{ model.count }}个用户</span>
      </div>
      <div>
        <el-select v-model="type" placeholder="请选择">
          <el-option label="全部" value=""></el-option>
          <el-option label="省级管理员" value="1"></el-option>
          <el-option label="市级管理员" value="3"></el-option>
          <el-option label="县级管理员" value="4"></el-option>
        </el-select>
        <el-input placeholder="输入用户名/姓名查询" v-model="name" class="width-300" @keyup.native.enter="newSearch">
          <el-button slot="append" type="primary" style="outline: none;" icon="el-icon-search"
            @click="newSearch"></el-button>
        </el-input>
        <!-- <el-button type="primary" class="ml-3" @click="exportExcel"
          >导出Excel<i class="el-icon-download"></i
        ></el-button> -->
      </div>
    </el-header>
    <el-main class="p-0 pt-2">
      <el-table :data="model.rows">
        <el-table-column label="序号" min-width="25" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 + model.pageSize * (model.pageIndex - 1) }}
          </template>
        </el-table-column>
        <el-table-column prop="account" label="用户账号" align="center"></el-table-column>
        <el-table-column prop="name" label="用户姓名" align="center"></el-table-column>
        <el-table-column prop="name" label="用户类型" align="center">
          <template slot-scope="scope">
            {{
            scope.row.type == "1"
            ? "省级管理员"
            : scope.row.type == "3"
            ? "市级管理员"
            : scope.row.type == "4"
            ? "县级管理员"
            : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="行政区域" align="center">
          <template slot-scope="scope">
            <span>{{ (scope.row.cityName || '') + (scope.row.areaName || '') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="作业单位" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.userCompany }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="remark" style="max-width: 80px;" label="备注" align="center">
          <template slot-scope="scope">
            {{
            scope.row.remark && scope.row.remark.length > 15
            ? scope.row.remark.substring(0, 15) + "..."
            : scope.row.remark
            }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="添加时间" align="center">
          <template slot-scope="scope">
            {{ $formatDateTime(scope.row.createdDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-tooltip content="重置密码" placement="top">
              <svg-icon @click="restPs(scope.row)" icon-class="reset-password" style="font-size: 1.2rem;"></svg-icon>
            </el-tooltip>
            <el-tooltip content="重新编辑" placement="top">
              <i class="el-icon-edit ml-3" style="font-size: 1.2rem;" @click="reEdit(scope.row)"></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="name" label="状态" align="center">
            <template slot-scope="scope">
              <el-tooltip
                :content="scope.row.status === 0 ? '启用' : '禁用'"
                placement="top"
              >
                <el-switch
                  @change="changeStatus(scope.row)"
                  :activeValue="1"
                  :inactiveValue="0"
                  v-model="scope.row.status"
                  active-color="#94C05A"
                  inactive-color="#aaa"
                >
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column> -->
      </el-table>
    </el-main>
    <el-pagination v-show="model.rows.length > 0" class="text-right py-3 pr-5 bg-white"
      @size-change="handleSizeChange" @current-change="val => this.model.pageLoad(val)"
      :current-page.sync="model.pageIndex" :page-sizes="[20, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper"
      :total="model.count" :pager-count="7">
    </el-pagination>
    <el-dialog :title="Boolean(ruleForm.id)? '修改用户' : '添加用户'" :close-on-click-modal="false"
      :visible.sync="outerVisible" @closed="clearRuleForm" width="700px">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" style="width: 600px;">
        <el-form-item label="用户账号" prop="account">
          <el-input v-model="ruleForm.account" placeholder="6-16位" :disabled="Boolean(ruleForm.id)"></el-input>
        </el-form-item>
        <el-form-item label="用户类型" prop="type">
          <el-select :disabled="Boolean(ruleForm.id)" v-model="ruleForm.type" placeholder="请选择用户类型"
            style="width: 450px;">
            <el-option label="省级管理员" value="1"></el-option>
            <el-option label="市级管理员" value="3"></el-option>
            <el-option label="县级管理员" value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="行政区域" prop="allName" v-show="(ruleForm.type != 1) && !Boolean(ruleForm.id)">
          <el-select v-model="ruleForm.cityId" placeholder="请选择市" style="width: 200px;" clearable>
            <el-option v-for="(val, key) in city" :filterable="true" :key="key" :label="val" :value="key">
            </el-option>
          </el-select>
          <el-select v-model="ruleForm.areaId" v-show="ruleForm.type == 4" placeholder="请选择区县" ref="area"
            clearable>
            <el-option v-for="(val, key) in area" :filterable="true" :key="key" :label="val" :value="key">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="!ruleForm.id">
          <el-input type="password" v-model="ruleForm.password" placeholder="6-16位，必须由字母(区分大小写)和数字组成"
            show-password></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="ruleForm.remark" :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="请输入备注，最长100汉字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="width-100" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="outerVisible = false" class="width-100">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-container>
</template>
<script>
import PagedList from "../../libs/PagedList";
import axios from "axios";
import pca from '@/libs/pca-code';
// 自定义密码验证
const validatePass = (rule, value, callback) => {
  if (value.length < 6 || value.length > 16) {
    callback(new Error("密码长度在 6 到 16 个字符"));
  } else if (!/^[a-zA-Z0-9_]{6,16}$/.test(value)) {
    callback(new Error("6-16位，必须由字母(区分大小写)和数字组成"));
  } else {
    callback();
  }
};

export default {
  name: "adminuser",
  title: "省级用户",
  data() {
    return {
      model: new PagedList("survey/user/getProvinceCityAreaAdmin", 20),
      name: "",
      type: "",
      outerVisible: false,
      ruleForm: {
        account: "",
        appType: "1",
        areaId: '',
        cityId: '',
        name: "",
        password: "",
        region: [],
        remark: "",
        type: "1"
      },
      rules: {
        account: [
          { required: true, message: "请输入省级用户账号", trigger: "blur" },
          { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
        ],
        type: [
          { required: true, message: "请选择用户类型", trigger: "change" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: "blur" }
        ],
        remark: [{ max: 100, message: "不超过100个字符", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.newSearch();
  },
  methods: {
    newSearch() {
      this.model.search({ type: this.type, name: this.name });
    },
    handleSizeChange(pageSize) {
      this.model.pageSize = pageSize
      this.newSearch();
    },
    addUser() {
      this.outerVisible = true;
    },
    /*exportExcel() {
      this.$exportExcel(
        `survey/excel/admin?mix=${this.keywords}&oauth=${
          this.$store.state.user.user.oauth
        }`
      );
    },*/
    restPs(user) {
      this.$confirm(`确认重置 ${user.name} 的密码为a123456 ?`, "确认重置密码", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.model.loading = true;
          axios
            .get(
              `survey/user/resetPwd?account=${encodeURIComponent(user.account)}`
            )
            .then(res => {
              if (res.data.code === "200") {
                this.$message({
                  type: "success",
                  message: "密码重置成功!"
                });
              } else {
                this.$codeError(res);
              }
            })
            .catch(error => {
              this.$catchError(error);
            })
            .finally(() => {
              this.model.loading = false;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置"
          });
        });
    },
    reEdit(row) {
      row.type = row.type.toString();
      this.ruleForm = Object.assign({}, row)
      this.$nextTick(() => {
        this.outerVisible = true;
      });
    },
    // 启用禁用(禁用功能暂时取消)
    changeStatus(user) {
      axios
        .get(
          `survey/user/updateStatus?id=${user.id}&status=${user.status}`,
          this.$paramsConvert()
        )
        .then(res => {
          if (res.data.code === "200") {
            this.$message({
              type: "success",
              message: "状态修改成功!"
            });
          } else {
            this.$codeError(res);
          }
        })
        .catch(error => {
          this.$catchError(error);
        });
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let url = "survey/user/addUser";
          if (this.ruleForm.id) {
            url = "survey/user/update";
          }
          if (this.ruleForm.areaId) {
            this.ruleForm.type = "4";
          }

          if (this.ruleForm.cityId && !this.ruleForm.areaId) {
            this.ruleForm.type = "3";
          }

          axios
            .post(url, this.ruleForm)
            .then(res => {
              if (res.data.code === "200") {
                this.$message({
                  type: "success",
                  message: this.ruleForm.id ? '修改成功' : "添加成功!"
                });
                this.outerVisible = false;
                this.newSearch();
              } else {
                this.$codeError(res);
              }
            })
            .catch(error => {
              this.$catchError(error);
            });
        } else {
          return false;
        }
      });
    },
    clearRuleForm() {
      this.ruleForm = {
        account: "",
        appType: "1",
        areaId: '',
        cityId: '',
        name: "",
        password: "",
        region: [],
        remark: "",
        type: "1"
      };
      // 重置验证器
      this.resetForm();
    },
    resetForm() {
      this.$refs["ruleForm"].resetFields();
    }
  },
  computed: {
    city() {
      return pca[610000]
    },
    area() {
      this.ruleForm.areaId = ''
      return this.ruleForm.cityId ? pca[this.ruleForm.cityId] : {}
    },
  }
};
</script>
